<?php

namespace App\Service\Common;

use App\Exception\ApiException;
use App\Model\CpsWalletLog;
use App\Model\CpsWallet;

class SpreadCoinOperateService extends SpreadCoinOperateInterface
{

    public function inc(
        int $sId,
        string $amount,
        string $argument,
        string $description = ''
    )
    {
        $this->checkNum($amount);

        $spreadInfo = $this->spreadAccount->getInfoById($sId);

        if (!$spreadInfo) {
            throw new ApiException('用户不存在');
        }

        $this->checkWallet($sId);

        $res = $this->cpsWallet->incCoinByUserId($sId, $amount);
        if (!$res || $res < 0) {
            throw new ApiException('账户异常');
        }

        $cpsWalletLogModel = new CpsWalletLog();

        $cpsWalletLogModel->s_id = $sId;
        $cpsWalletLogModel->p_id = $spreadInfo->parent_id;
        $cpsWalletLogModel->type = 1;
        $cpsWalletLogModel->value = $amount;
        $cpsWalletLogModel->argument = $argument;
        $cpsWalletLogModel->remark = $description;

        if (!$cpsWalletLogModel->save()) {
            throw new ApiException('添加账户记录异常');
        }

        return true;

//        $
    }

    public function dec(
        int $sId,
        string $amount,
        string $argument,
        string $description = ''
    )
    {

    }

    private function checkWallet($userId)
    {
        $wallet = $this->cpsWallet->getInfoById($userId);

        if (!$wallet) {
            $walletModel = new CpsWallet();

            $walletModel->s_id = $userId;
            $walletModel->balance = 0;

            $walletModel->save();
        }
    }
}